package com.xiegk.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * redis 分布式锁版本 1
 * 简单实现 - 仍然会存在并发问题
 *
 * @author xgk
 * @date 2022/2/20
 */
@Component
public class RedisLockVersion01 {
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 锁
     *
     * @param key           键
     * @param timeOutSecond 过期时间
     */
    public void lock(String key, int timeOutSecond) {
        for (; ; ) {
            Boolean exit = redisTemplate.opsForValue().setIfAbsent(key, "aaa", timeOutSecond, TimeUnit.SECONDS);
            if (exit) {
                break;
            }
        }
    }

    /**
     * 释放锁
     *
     * @param key 键
     */
    public void unlock(String key) {
        redisTemplate.delete(key);
    }
}
